import { createRouter, createWebHistory } from 'vue-router'

import { useUserStore } from '@/stores/userStore'
import AppLayout from '@/layouts/AppLayout.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/Index.vue'),
    },
    {
      path: '/',
      component: AppLayout,
      redirect: '/index',
      children: [
        {
          path: 'index',
          name: 'index',
          component: () => import('@/views/Index.vue'),
        },
        {
          path: 'files',
          name: 'files',
          component: () => import('@/views/fileManage/Index.vue'),
        },
        {
          path: 'users',
          name: 'users',
          component: () => import('@/views/userManage/Index.vue'),
        },
        {
          path: 'tags',
          name: 'tags',
          component: () => import('@/views/tagManage/Index.vue'),
        },
        {
          path: 'recycle-bin',
          name: 'recycle-bin',
          component: () => import('@/views/fileManage/RecycleBin.vue'),
        },
        {
          path: 'roles',
          name: 'roles',
          component: () => import('@/views/roleManage/Index.vue'),
        },
        {
          path: 'logs',
          name: 'logs',
          component: () => import('@/views/logManage/Index.vue'),
        },
        {
          path: 'me',
          name: 'me',
          component: () => import('@/views/userManage/UserProfile.vue'),
        },
      ],
      meta: { requiresAuth: true },
    },
    {
      path: '/editor',
      name: 'editor',
      component: () => import('@/views/editor/Index.vue'),
    },
  ],
})

// 全局导航守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()

  // 如果访问需要登录的页面，且未登录
  if (to.meta.requiresAuth && !userStore.isLogin) {
    next('/login')
  } else {
    next()
  }
})

export default router
